import panelsConf from '@/components/common/echart/echart-panels-config.js';
import echartUtil from '@/components/common/echart/echart-util.js';
import { genRulesByKey } from '@/utils/rules';
import { isEmpty, objHas } from '@/utils/util.js';
import { merge } from 'lodash';
import { mapState } from 'vuex';

export default {
  props: {
    index: Number, // 数组项索引，不传则为公共属性
    form: Object,
  },
  inject: {
    panelWid: {
      default: '',
    },
  },
  computed: {
    ...mapState({
      panelApiData: state => state.VisualComponentsModule.panelApiData,
      panelConfigs: state => state.VisualComponentsModule.panelConfigs,
    }),
    serieNames() {
      // 用于系列名下拉
      let names = [];
      const hasSerieName = this.panelApiData.some(n => objHas(n, 's'));
      if (hasSerieName) {
        const arr = this.panelApiData.map(n => n.s);
        const nameList = Array.from(new Set(arr));
        names = nameList.map(n => {
          const value = isEmpty(n) ? '' : `${n}`;
          return { label: n, value };
        });
      }
      return names;
    },
    componentName() {
      const name = this.form.echart && this.form.echart._componentName;
      return name;
    },
    panelConfig() {
      const emptyConfig = {
        widgetInstanceId: '',
        siteId: '',
        property: {},
        data: {
          tableData: [],
        },
        events: {},
      };
      return this.panelConfigs[this.panelWid] || emptyConfig;
    },
  },
  methods: {
    fixPath(path) {
      let _path = path;
      if (isNaN(this.index)) {
        _path = _path.replace('.[x]', '');
      } else {
        _path = _path.replace('.[x]', `.${this.index}`);
      }
      return _path;
    },

    /**
     * 合并对象，原对象及其属性内存地址不变
     * @param  {Object} orgObj    原对象
     * @param  {Object} dataObj 数据更新对象，属性将会合并到原对象
     */
    mergeObj(orgObj, dataObj) {
      merge(orgObj, dataObj);
    },

    isValid(path, serieType) {
      const val = echartUtil.getDfVal(path, this.form, serieType);
      return val;
    },

    // 组件配置面板是否出现某属性配置菜单
    hasProp(key) {
      const { _componentName } = this.form.echart;
      const conf = panelsConf[_componentName] || {};
      return conf[key];
    },

    // 是否时间轴或数据轴
    isTimeValueAxis(xy = 'x') {
      let axis;
      if (xy === 'x') {
        axis = this.form.echart.xAxis;
      } else {
        axis = this.form.echart.yAxis;
      }

      if (Array.isArray(axis)) {
        axis = axis[this.index];
      }

      const type = axis && axis.type;
      if (!type) {
        return false;
      }
      return ['time', 'value'].includes(type);
    },

    genRulesByKey,
  },
};
